const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("uni-id-users");
module.exports = class UserService extends Service {
	clear(){
		return collection.where({
		  _id: dbCmd.exists(true)
		}).remove();
	}
	async register(username,password){
		const res = await uniID.register({
			username,
			password,
			needPermission:true
		})
		if(res.code==0){
			await collection.doc(res.uid).update({
				balance:0,
				integral:0
			})
			return response.success({
				token:res.token,
				tokenExpired:res.tokenExpired,
				uid:res.uid
			});
		}else{
			return response.fail(res.message);
		}
	}
	async login(username,password){
		const res = await uniID.login({
			username,
			password,
			queryField: ['username', 'email', 'mobile']
		})
		if(res.code==0){
			return response.success({
				token:res.token,
				tokenExpired:res.tokenExpired,
				username:res.username
			});
		}else{
			return response.fail(res.message);
		}
	}
	async getUser(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		ctx.data.user_id=ctx.uid
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		const res=await dbJQL.collection('uni-id-users').where('_id == $cloudEnv_uid').get({
			getOne:true
		})
		const res1=await dbJQL.collection('goods-records').where('user_id == $cloudEnv_uid').get()
		const res2=await dbJQL.collection('goods-favorites').where('user_id == $cloudEnv_uid').get()
		if(res.code==0){
			return response.success({
				...res.data,
				records_count:res1.data.length,
				favorites_count:res2.data.length
			})
		}else{
			return response.fail(res.message)
		}
	}
	async loginByGitee(user){
		const res=await collection.where({
			gitee_id: user.id
		}).get()
		//uniCloud.logger.log(res)
		const time=(new Date()).getTime()
		let redirect_uri='https://zouchengxin.gitee.io/vite-vue3-shop/tabbar/home?token='
		if(res.affectedDocs==0){
			const res1=await collection.add({
				username:user.login,
				nickname:user.name,
				email:user.email,
				avatar:user.avatar_url,
				gitee_id:user.id,
				register_date:time,
				balance:0,
				integral:0
			})
			if(res1.id){
				const res2=uniID.createToken({
					uid:res1.id
				})
				if(res2.token){
					const res3=await collection.doc(res1.id).update({
					  token:[res2.token]
					});
					redirect_uri+=res2.token
				}
			}
			this.ctx.headers = {
				'Location': redirect_uri
			}
			this.ctx.status=302
		}else{
			if(res.data.length>0){
				const res3=uniID.createToken({
					uid:res.data[0]._id
				})
				if(res3.token){
					const res4=await collection.doc(res.data[0]._id).update({
						username:user.login,
						nickname:user.name,
						email:user.email,
						avatar:user.avatar_url,
						last_login_date:time,
					  token:[res3.token]
					});
					redirect_uri+=res3.token
				}
				this.ctx.headers = {
					'Location': redirect_uri
				}
				this.ctx.status=302
			}
		}
	}
	async loginByQQ(openid,user){
		const res=await collection.where({
			qq_openid: openid
		}).get()
		//uniCloud.logger.log(res)
		const time=(new Date()).getTime()
		let redirect_uri='https://zouchengxin.gitee.io/vite-vue3-shop/tabbar/home?token='
		if(res.affectedDocs==0){
			const res1=await collection.add({
				username:user.nickname,
				nickname:user.nickname,
				avatar:user.figureurl_2,
				qq_openid:openid,
				register_date:time,
				balance:0,
				integral:0
			})
			if(res1.id){
				const res2=uniID.createToken({
					uid:res1.id
				})
				if(res2.token){
					const res3=await collection.doc(res1.id).update({
					  token:[res2.token]
					});
					redirect_uri+=res2.token
				}
			}
			this.ctx.headers = {
				'Location': redirect_uri
			}
			this.ctx.status=302
		}else{
			if(res.data.length>0){
				const res3=uniID.createToken({
					uid:res.data[0]._id
				})
				if(res3.token){
					const res4=await collection.doc(res.data[0]._id).update({
						username:user.nickname,
						nickname:user.nickname,
						avatar:user.figureurl_2,
						last_login_date:time,
					  token:[res3.token]
					});
					redirect_uri+=res3.token
				}
				this.ctx.headers = {
					'Location': redirect_uri
				}
				this.ctx.status=302
			}
		}
	}
	async loginByAliPay(user){
		const res=await collection.where({
			ali_id: user.userId
		}).get()
		//uniCloud.logger.log(res)
		const time=(new Date()).getTime()
		let redirect_uri='https://zouchengxin.gitee.io/vite-vue3-shop/tabbar/home?token='
		if(res.affectedDocs==0){
			const res1=await collection.add({
				username:user.userId,
				nickname:user.userId,
				ali_id: user.userId,
				register_date:time,
				balance:0,
				integral:0
			})
			if(res1.id){
				const res2=uniID.createToken({
					uid:res1.id
				})
				if(res2.token){
					const res3=await collection.doc(res1.id).update({
					  token:[res2.token]
					});
					redirect_uri+=res2.token
				}
			}
			this.ctx.headers = {
				'Location': redirect_uri
			}
			this.ctx.status=302
		}else{
			if(res.data.length>0){
				const res3=uniID.createToken({
					uid:res.data[0]._id
				})
				if(res3.token){
					const res4=await collection.doc(res.data[0]._id).update({
						username:user.userId,
						nickname:user.userId,
						ali_id: user.userId,
						last_login_date:time,
					  token:[res3.token]
					});
					redirect_uri+=res3.token
				}
				this.ctx.headers = {
					'Location': redirect_uri
				}
				this.ctx.status=302
			}
		}
	}
	async loginByWX(openid,user){
		const res=await collection.where({
			wx_openid: openid
		}).get()
		//uniCloud.logger.log(res)
		const time=(new Date()).getTime()
		let redirect_uri='https://zouchengxin.gitee.io/vite-vue3-shop/#/tabbar/home?token='
		if(res.affectedDocs==0){
			const res1=await collection.add({
				username:user.nickname,
				nickname:user.nickname,
				avatar:user.headimgurl,
				wx_openid:openid,
				wx_unionid:user.openid,
				register_date:time,
				balance:0,
				integral:0
			})
			if(res1.id){
				const res2=uniID.createToken({
					uid:res1.id
				})
				if(res2.token){
					const res3=await collection.doc(res1.id).update({
					  token:[res2.token]
					});
					redirect_uri+=res2.token
				}
			}
			this.ctx.headers = {
				'Location': redirect_uri
			}
			this.ctx.status=302
		}else{
			if(res.data.length>0){
				const res3=uniID.createToken({
					uid:res.data[0]._id
				})
				if(res3.token){
					const res4=await collection.doc(res.data[0]._id).update({
						username:user.nickname,
						nickname:user.nickname,
						avatar:user.headimgurl,
						last_login_date:time,
						wx_unionid:user.openid,
					  token:[res3.token]
					});
					redirect_uri+=res3.token
				}
				this.ctx.headers = {
					'Location': redirect_uri
				}
				this.ctx.status=302
			}
		}
	}
};